package com.jule.teenpatti.mail.network.protocol.reqs;

import JoloProtobuf.AuthSvr.JoloAuth;
import com.jule.teenpatti.base.enums.ErrorCodeEnum;
import com.jule.teenpatti.mail.network.protocol.ClientReq;
import com.jule.teenpatti.mail.network.protocol.acks.JoloAuth_MailListAck_600021;
import com.jule.teenpatti.mail.network.protocol.acks.JoloAuth_RedDotAck_600020;
import com.jule.teenpatti.mail.service.MailService;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class JoloAuth_MailListReq_600021 extends ClientReq {
    public JoloAuth_MailListReq_600021(int functionId) {
        super(functionId);
    }

    private JoloAuth.JoloAuth_MailListReq req;

    @Override
    public void readPayLoadImpl(ByteBuf buf) throws Exception {
        byte[] blob = new byte[buf.readableBytes()];
        buf.readBytes(blob);
        req = JoloAuth.JoloAuth_MailListReq.parseFrom(blob);
    }

    @Override
    public void processImpl() throws Exception {
        log.debug("收到消息-> " + functionId + ", reqNum-> " + header.reqNum + ", req->" + req.toString());
        JoloAuth.JoloAuth_MailListAck.Builder ack = JoloAuth.JoloAuth_MailListAck.newBuilder();
        String userId = req.getUserId();
        //强制刷新邮件列表1强制0不需要刷新
        int forced2Refresh = req.getForced2Refresh();
        ack.setUserId(userId).setResult(1);
        try{
            if(forced2Refresh==1){
                MailService.getInstance().loadMailByUserId(userId);
            }

            List<JoloAuth.JoloAuth_MailItem> mailItems = MailService.getInstance().getMailListByUserId(userId);
            ack.addAllMailItem(mailItems);

            ctx.writeAndFlush(new JoloAuth_MailListAck_600021(ack.build(),header));
        }catch(Exception ex){
            ack.setResult(0);
            ack.setResultMsg(ErrorCodeEnum.GAME_50002_2.getCode());
            ctx.writeAndFlush(new JoloAuth_RedDotAck_600020(ack.build(),header));

            log.error(ex.getMessage(),ex);
        }

    }
}
